package com.cictec.middleware.gps.caculate.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.NumberUtil;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.commons.utils.gps.GpsUtils;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.core.pojo.ESEnterOutEntity;
import com.cictec.middleware.core.pojo.ESPositionEntity;
import com.cictec.middleware.feign.elasticsearch.MiddlewareElasticsearchService;
import com.cictec.middleware.gps.caculate.BusTripEngine;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.caculate.entity.BusEngine;
import com.cictec.middleware.gps.engine.caculate.entity.BusMileage;
import com.cictec.middleware.gps.engine.caculate.entity.BusMileageData;
import com.cictec.middleware.gps.engine.caculate.entity.BusMileageSegment;
import com.cictec.middleware.gps.engine.caculate.entity.BusTrip;
import com.cictec.middleware.gps.engine.exception.BusPositionHandlerException;
import com.cictec.middleware.gps.engine.position.BusPositionHandlerService;
import com.cictec.middleware.gps.engine.utils.ESPositionEntityConvertUtils;
import com.cictec.middleware.gps.engine.utils.MultiLogUtil;
import com.cictec.middleware.gps.service.BusDriverService;
import com.cictec.middleware.gps.service.ScheduleService;
import com.cictec.middleware.gps.service.WarnMsgService;

/**
 * 里程计算服务，提供里程计算相关方法
 * @author ql
 */
@Component
public class BusMileageService extends BusPositionHandlerService {
	
	public static Logger logger = LoggerFactory.getLogger(BusMileageService.class);

	@Autowired
	protected WarnMsgService warnMsgService;
	@Autowired
	protected ScheduleService scheduleService;
	@Autowired
	protected BusDriverService busDriverService;
	@Autowired
	protected BusTripEngine busTripEngine;
	@Autowired
	protected GpsCaculateRedisService dataStorageToRedisService;
	@Autowired
	protected MiddlewareElasticsearchService middlewareElasticsearchService;
	
	/**
	 * 刷新基础信息
	 * @param entity
	 */
	public void refrashBaseInfo(BusMileageData entity){
		String date = entity.date;
		String busUuid = entity.busUuid;
		/* ******* 基础数据更新 start **********************************/
		// 更新当前车辆在线路上的发车标识为未发车
		scheduleService.updateScheduleDepartureFlag(date, busUuid);
		
//		logger.debug("清除报警信息【偏线、停车、甩站、压站】，重新计算获取");
		warnMsgService.deleteWarn(date, Constants.VAL_BUS_STATUS_7, busUuid);	// 删除当前【偏线】报警，重新计算获取
		warnMsgService.deleteWarn(date, Constants.VAL_BUS_STATUS_9, busUuid);	// 删除当前【停车】报警，重新计算获取
		warnMsgService.deleteWarn(date, Constants.VAL_BUS_STATUS_13, busUuid);	// 删除当前【甩站】报警，重新计算获取
		warnMsgService.deleteWarn(date, Constants.VAL_BUS_STATUS_14, busUuid);	// 删除当前【压站】报警，重新计算获取
		/* ******* 基础数据更新 end **********************************/
		
		busDriverService.refreshDriverSignIn(busUuid, date);
	}
	
	/**
	 * 剔除无效的切换信息
	 * @param entity
	 */
	public void beautifyOrgPositions(BusMileageData entity){
		
		List<TimingPoint> orgTimingPoints = entity.orgTimingPoints;
		
		List<TimingPoint> pointList = new ArrayList<TimingPoint>();
//		String devLineId = null;
		for (int i = 0; i < orgTimingPoints.size(); i++) {
			pointList.add(orgTimingPoints.get(i));
			
//			TimingPoint point = orgTimingPoints.get(i);
//			if(devLineId == null){
//				devLineId = point.getDevLineId();
//				TimingPoint tmp = new TimingPoint();
//				BeanUtils.copyProperties(point, tmp);
//				tmp.setAttribute("index", i+"");
//				pointList.add(tmp);
//			}
//			if(!devLineId.equals(point.getDevLineId())){
//				devLineId = point.getDevLineId();
//				TimingPoint tmp = new TimingPoint();
//				BeanUtils.copyProperties(point, tmp);
//				tmp.setAttribute("index", i+"");
//				pointList.add(tmp);// 当前线路第一个点游标，即标识线路在此点开始切换了
//			}
		}
		entity.beautyOrgTimingPoints = pointList;
	}

	/**
	 * 位置点信息回放
	 * @param entity
	 */
	public void playback(BusMileageData entity){
		
		List<TimingPoint> busTimingPoints = entity.beautyOrgTimingPoints;
		if (busTimingPoints.size() > 1) {
			MultiLog log = MultiLogUtil.getBusMileageLog(entity.date, entity.busInstance);
			
			// 1、【位置信息】数据点执行逻辑
			List<BusMileageSegment> mileageSegmentList = new ArrayList<BusMileageSegment>();
			BusMileageSegment mileageSegment = new BusMileageSegment();// 当前线路里程段
			BusInstance busInstance = entity.busInstance;
			for (int i = 0; i < busTimingPoints.size(); i++) {
				
				TimingPoint timingPoint = busTimingPoints.get(i);
				timingPoint.setAttribute(Constants.CALCULATE_MILEAGE, "calculateMilage");// 添加里程计算标识
				timingPoint.setHistoryFlag(Constants.MSG_INFO_POSITION_HISTORY_DATA_FLASE);// 设置为非历史数据标识
				timingPoint.setAttribute(Constants.MSG_INFO_POSITION_HISTORY_DATA, Constants.MSG_INFO_POSITION_HISTORY_DATA_FLASE);	// 设置为非历史数据标识
				
				busInstance.setTime(timingPoint.getTime());	// 设置busInstance对象当前时间【位置点上传时间】
				busInstance.setAttributes(timingPoint.getAttributes());
				busInstance.addTimingPoint(timingPoint);		// 添加到实时数据队列中，计算用
				/*
				 * 1、判定是否是同一个线路
				 * 		【注意】子线路信息
				 */
				playbackPoint(busInstance);
				
				if(busInstance.isEnterOut()){
					// 如果是进出站信息点，保存
					TimingPoint entoutPoint = new TimingPoint();
					entoutPoint.setTime(busInstance.getTime());
					entoutPoint.setAttributes(busInstance.getAttributes());
					mileageSegment.enterOutPoints.add(entoutPoint);
				}
				
				if(PMSUtils.isEmpty(mileageSegment.busUuid)){
					logger.debug(">>>>>>>>>>>>>>>>>位置信息回放 lineName:{} busNumber:{} ", busInstance.getLineName(), busInstance.getBusNumber());
					log.debug(">>>>>>>>>>>>>>>>>位置信息回放 lineName:{} busNumber:{} ", busInstance.getLineName(), busInstance.getBusNumber());
					
					mileageSegment.busUuid = entity.busUuid;
					mileageSegment.devCode = entity.devCode;
					mileageSegment.plate = entity.plate;
					mileageSegment.lineUuid = busInstance.getLineUuid();
					mileageSegment.lineName = busInstance.getLineName();
					mileageSegment.date = entity.date;
				}
				
				if(isSameSegment(mileageSegment, busInstance)){
					doSameSegment(mileageSegment, busInstance);
				}else{
					mileageSegmentList.add(mileageSegment);
					
					logger.debug(">>>>>>>>>>>>>>>>>位置信息回放，线路信息切换 lineName:{} busNumber:{} ", busInstance.getLineName(), busInstance.getBusNumber());
					log.debug(">>>>>>>>>>>>>>>>>位置信息回放，线路信息切换 lineName:{} busNumber:{} ", busInstance.getLineName(), busInstance.getBusNumber());

					// 创建新的里程段
					mileageSegment = new BusMileageSegment();
					doSameSegment(mileageSegment, busInstance);
				}
				
				if(i == busTimingPoints.size() -1){
					// 最后一个点，计算该里程段
					mileageSegmentList.add(mileageSegment);
				}
			}
			entity.mileageSegments = mileageSegmentList;
		}
	}
	
	/**
	 * 判定是否线路信息切换了（可以扩展此方法做详细配置）
	 * @param mileageSegment
	 * @param busInstance
	 * @return
	 */
	private boolean isSameSegment(BusMileageSegment mileageSegment, BusInstance busInstance){
		if(mileageSegment.lineUuid.equals(busInstance.getLineUuid())){
			return true;
		}
		return false;
	}
	
	/**
	 * 记录位置点信息,记录该线路段有效点、漂移点、没有上下行的点等【可扩展】
	 * @param mileageSegment
	 * @param busInstance
	 */
	private void doSameSegment(BusMileageSegment mileageSegment, BusInstance busInstance){

		mileageSegment.totalPointCount ++;	// 总点数
		
		/* *************** 存储当前点数据 start*******************************************************/
		// 过滤掉漂移点
		if(!busInstance.isInDrift()){
			// 有上下行
			if(busInstance.getLineType() != null){
				mileageSegment.caculatePoints.add(new TimingPoint(busInstance.getTime(), busInstance.getAttributes()));
			}else{
				// 没有上下行的点
				mileageSegment.noLineTypePoint.add(new TimingPoint(busInstance.getTime(), busInstance.getAttributes()));
			}
		}else{
			// 漂移点
			mileageSegment.driffPoints.add(new TimingPoint(busInstance.getTime(), busInstance.getAttributes()));
		}
		/* *************** 存储当前点数据 end *******************************************************/
	}
	
	/**
	 * 位置点回放
	 * @param busInstance
	 */
	public void playbackPoint(BusInstance busInstance) {
		try {
			busPositionHandler(busInstance);
		} catch (BusPositionHandlerException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 位置业务逻辑计算
	 * 
	 * @param busInstance
	 * @throws busPositionHandlerException
	 */
	private void busPositionHandler(BusInstance busInstance) throws BusPositionHandlerException {


		// 第一步：漂移判断处理
		busPositionDriftHandler.onHandler(busInstance);
		if (busInstance.isInDrift()) {
			return;
		}
		
		if(busInstance.isEnterOut()){
			busInstance.setCurrentStation(busInstance);
		}
		
		// 司机签到信息处理
		busPositionDriverHandler.onHandler(busInstance);
		
		// 运营状态判断处理
		busPositionOperationHandler.onHandler(busInstance);

		// 待发区判断（车辆处于运营状态，进行）
		busPositionStandbyHandler.onHandler(busInstance);

		// 方向判断 根据坐标点判断线路方向（待发区判断完毕！ ）
		busPositionLineTypeHandler.onHandler(busInstance);

		// 偏线判断（存在线路上下行 ）
		busPositionDeviateHandler.onHandler(busInstance);

		// 进出站信息
		busPositionStationHandler.onHandler(busInstance);
		// 相对距离
		busPositionRelativeDistanceHandler.onHandler(busInstance);
		// 第六步 班次、趟次计算
		busPositionShiftAndTripHandler.onHandler(busInstance);

		// 保存进出站 【里程计算过程中】
		// busPositionCacheHandler.saveEnterOutToCache(busInstance);

		// 报警信息
		busPositionAlarmsHandler.onHandler(busInstance);
		
//		busPositionDistributeHandler.showPostionLog(busInstance);
		// 位置信息存储到redis、站点es ，并发送数据到 apolo
//		busPositionDistributeHandler.onHandler(busInstance);

	}


	/**
	 * 里程段里程计算
	 */
	public void caculateSegment(BusMileageData entity){
		List<BusMileageSegment> mileageSegments = entity.mileageSegments;
		for (BusMileageSegment mileageSegment : mileageSegments) {
			caculateSegment(mileageSegment);
			
		}
	}
	
	public void caculateSegment(BusMileageSegment segment){
		/*
		 * 1、该线路段趟次信息计算
		 * 2、该线路段里程信息计算
		 */
//		mileageSegment.enterOutPoint;
		
		BusEngine busEngile = segment.busEngile;
		busEngile.setLineid(segment.lineUuid);
		busEngile.setLinename(segment.lineName);
		busEngile.setPlate(segment.plate);
		busEngile.setBusid(segment.busUuid);
		
		caculateSegmentTrip(segment);
		
		caculateSegmentMileage(segment);
		
	}
	
	/**
	 * 计算线路里程段趟次嘻嘻你
	 */
	public void caculateSegmentTrip(BusMileageSegment segment){
		
		List<BusTrip> busTrips = busTripEngine.getTrip(segment.enterOutPoints);
		
		BusEngine busEngile = segment.busEngile;
		busEngile.setBusTrips(busTrips);
		
		for (BusTrip busTrip : busTrips) {
			scheduleService.updateBusSchedule(busTrip.getLineid(), busTrip.getLinetype(), busTrip.getUuid(), busTrip.getDoduuid(), busTrip.getStartTime(), busTrip.getEndTime());
		}
		
		MultiLog log = MultiLogUtil.getBusMileageLog(segment.date, segment.devCode, segment.plate);
		for (int i = 0; i < busTrips.size(); i++) {
			BusTrip trip = busTrips.get(i);
			logger.debug("第{}趟：lineType：{}\t时间：{} 至 {}\tseq：{} 至 {}, driverUuid:{}", (i + 1),
					trip.getLinetype(),
					DateUtils.formatTime(trip.getStartTime()), DateUtils.formatTime(trip.getEndTime()),
					trip.getStartseq(), 
					trip.getEndseq(),
					trip.getDoduuid()
					);
			log.debug("第{}趟：lineType：{}\t时间：{} 至 {}\tseq：{} 至 {}, driverUuid:{}", (i + 1),
					trip.getLinetype(),
					DateUtils.formatTime(trip.getStartTime()), DateUtils.formatTime(trip.getEndTime()),
					trip.getStartseq(), 
					trip.getEndseq(),
					trip.getDoduuid()
					);
		}
	}
	
	
	public void caculateSegmentMileage(BusMileageSegment segment){
		MultiLog log = MultiLogUtil.getBusMileageLog(segment.date, segment.devCode, segment.plate);
		
		List<TimingPoint> points = segment.caculatePoints;
		checkDeviateStatus(points);	// 校正数据，三个点，校正中间点的位置偏线状态【中间数据删除掉】
		
		BusEngine busEngile = segment.busEngile;
		if(points.size() > 0){
			busEngile.setStartDate(points.get(0).getTime());
			busEngile.setEndDate(points.get(points.size() - 1).getTime());
		}
		
		
		List<BusMileage> busMileages = caculateMileage(segment.caculatePoints);
		busEngile.setBusMileages(busMileages);
		segment.busEngile = busEngile;
		
	}
	
	public List<BusMileage> caculateMileage(List<TimingPoint> points){
		
		MultiLog log = null;
		if(points.size() > 0){
			TimingPoint point = points.get(0);
			log = MultiLogUtil.getBusMileageLog(DateUtils.formatDate(point.getTime()), point.getDevCode(), point.getBusNumber());
		}
		
		checkDeviateStatus(points);	// 校正数据，三个点，校正中间点的位置偏线状态【中间数据删除掉】
		
		
		// 里程统计
		List<BusMileage> busMileages = new ArrayList<BusMileage>();		// 里程统计 数组
		BusMileage currentBusMileage = new BusMileage();				// 当前里统计对象
		
		int size = points.size();
		for (int i = 0; i < size; i++) {
			// 里程段计算
			TimingPoint currentPoint = points.get(i);
			TimingPoint nextPoint = i+1 < size ?  points.get(i + 1) : null;	// 如果是最后一个点
			
			// 获取当前点的里程类型
			String currentMileageType = getMileageType(currentPoint);	
			
			// 里程统计标识 0:非运营、1：运营
			currentBusMileage = calculateSegmentMileage(currentMileageType, busMileages, currentBusMileage, currentPoint, nextPoint);
		}
		
		/*
		 * 运营时间状态 
		 * 	0：【非运营】不在运营时间内 
		 *  1：【运营】在运营时间内
		 */
		double milage0 = 0;
		double milage1 = 0;
		for (BusMileage busMileage : busMileages) {
			if(busMileage.getType().equals("0")){
				milage0 = NumberUtil.add(milage0, busMileage.getMileage());
			}else{
				milage1 = NumberUtil.add(milage1, busMileage.getMileage());
			}
		}
		milage0 = NumberUtil.round(milage0, 2);
		milage1 = NumberUtil.round(milage1, 2);
		logger.debug("运营里程：{} 非运营里程：{}", milage1, milage0);
		log.debug("运营里程：{} 非运营里程：{}", milage1, milage0);
		return busMileages;
	}

	/**
	 * 校正数据，三个点，校正中间点的位置偏线状态【中间数据删除掉】
	 * @param points
	 * @param index
	 */
	private void checkDeviateStatus(List<TimingPoint> points) {

//		logger.debug("一共 {} 个位置信息",busCPPoints.size());
		
		for (int index = 0; index < points.size(); index++) {
			String currentPx = points.get(index).getStatusDeviate();
			if (index + 2 < points.size()) {
				String nextPx = points.get(index + 1).getStatusDeviate();
				String nextnextPx = points.get(index + 2).getStatusDeviate();

//				logger.debug("nextPx:{}, nextnextPx:{}",nextnextPx,nextnextPx);
				
				if (currentPx.equals(nextnextPx) && !currentPx.equals(nextPx)) {
					points.remove(index + 1);
				}
			} else {
				// 最后2个点
				if (index + 1 < points.size()) {
					String nextPx = points.get(index + 1).getStatusDeviate();
					if (!currentPx.equals(nextPx)) {
						points.remove(index + 1);
					}
				}
			}
		}
	}
	
	/**
	 * 获取当前点的里程类型
	 * @param currentPoint
	 * @return
	 */
	private String getMileageType(TimingPoint currentPoint){
		String mileageType = currentPoint.getStatusInOperateTime();	// 里程类型，默认运营状态判定
		
		/*************** 调度申请 start****************************/
		String scheduleApplayYY = PropertiesUtils.getString("schedule.apply.yunying", "222");	// 这里默认是目前是随便定义的
		String scheduleApplay = currentPoint.getScheduApply();// 调度申请
		if(!PMSUtils.isEmpty(scheduleApplay)){
			if(!scheduleApplay.equals(scheduleApplayYY)){
				mileageType = scheduleApplay;	// 调度申请里程
			}else if(scheduleApplay.equals(scheduleApplayYY)){
//				mileageType = "1";// 里程统计标识 0:非运营、1：运营
			}
		}
		/*************** 调度申请 end****************************/
		
		/*************** 包车计划 start****************************/
		boolean busCharter = PropertiesUtils.getBoolean("system.parameter.busCharter", false);
		if(busCharter){
			// 此参数在运营状态判定中设置
			if(currentPoint.containsAttribute("busCharter")){
				mileageType = currentPoint.getBusCharter();	// 包车计划里程，非运营里程
				
			}
		}
		/*************** 包车计划 end****************************/
		
		return mileageType;
	}
	
	/**
	 * 计算两个点的里程
	 * @param type				里程统计标识  0:非运营、1：运营
	 * @param busMileages		里程统计对象数组
	 * @param busMileage		当前里程段对象
	 * @param currentPoint		当前位置点
	 * @param nextPoint			下一个位置点
	 * @param date				日期
	 * @param plate				车牌号
	 */
	private BusMileage calculateSegmentMileage(String type, List<BusMileage> busMileages, BusMileage busMileage, TimingPoint currentPoint, TimingPoint nextPoint){
		
		/*
		 * 根据传进来的 统计类型判定 type: 0:运营、1：非运营
		 *  	1、遇到第一个未指定
		 *  		首先判断 是否存在运营标识，不存在的话 设置为非运营
		 *      2、如果存在运营标识，判定是否发生状态反转（即：非运营 -> 运营，或者 运营->非运营）
		 *      	如果发生状态反转，设置该时间点里程统计结束
		 */
		 
		// 两个点的时间差
		Long timeDiffer = nextPoint == null ? null : nextPoint.getTime().getTime() - currentPoint.getTime().getTime();
		
		
		if (busMileage.getType() == null) {
			busMileage.setType(type);
			busMileage.setStartDate(currentPoint.getTime());
			busMileage.setDoduuid(currentPoint.getDriverUuid());
			busMileage.setDriverName(currentPoint.getDriverName());
		}
		else if (!busMileage.getType().equals(type) 
				|| !busMileage.getDoduuid().equals(currentPoint.getDriverUuid())
				|| nextPoint == null
				|| timeDiffer == null ? true : timeDiffer > 60 * 1000 * 15
				) {
			// 当前里程段结束
			busMileage = currentCalculateMileageEnd(type, busMileages, busMileage, currentPoint, nextPoint, null);
		}

		/*
		 * 如果 连个时间点的数据未漂移，计算距离并更新到该段里程中
		 */
		
		if (!currentPoint.isInDeviate()) {
			String currentLatitude = currentPoint.getLatitude();
			String currentlongitude = currentPoint.getLongitude();
			
			if(nextPoint != null){
				String nextLatitude = nextPoint.getLatitude();
				String nextLongitude = nextPoint.getLongitude();
				
				double leng = GpsUtils.getDistance(currentLatitude, currentlongitude, nextLatitude, nextLongitude);
				// 更新当前里程段的 里程数据
				double oldLeng = busMileage.getMileage();
				busMileage.setMileage(oldLeng +leng);
//				NumberUtil.round(oldLeng +leng, 2);
//				busMileage.updateCurrentTypMielage(leng);
//				logger.debug("type:{},两点间的里程：{}, 总里程：{}", type, leng, (oldLeng +leng));
			}
		}
		
		return busMileage;
	}
	
	private BusMileage currentCalculateMileageEnd(String type, List<BusMileage> busMileages, BusMileage busMileage, TimingPoint currentPoint, TimingPoint nextPoint, MultiLog log){
		/*
		 * 当统计状态发证反转时候，结束该段里程统计
		 */
		
		// 设置 运营结束时间
		busMileage.setEndDate(currentPoint.getTime());

		
		logger.info("{}\t时间：{} 至 {} \t里程：{}, 司机：{}, \t\tdata:{}", 
				busMileage.getType().equals("0") ? "【非运营】" : (busMileage.getType().equals("1") ? "【运营】" : "【"+busMileage.getType()+"】"),
				DateUtils.formatDate(busMileage.getStartDate(), "HH:mm:ss"),
				DateUtils.formatDate(busMileage.getEndDate(), "HH:mm:ss"),
				busMileage.getMileage(),
				busMileage.getDriverName(),
				JSON.toJSONString(busMileage)
				);
		if(log != null){
			log.debug("{}\t时间：{} 至 {} \t里程：{}, 司机：{}, \t\tdata:{}", 
					busMileage.getType().equals("0") ? "【非运营】" : (busMileage.getType().equals("1") ? "【运营】" : "【"+busMileage.getType()+"】"),
							DateUtils.formatDate(busMileage.getStartDate(), "HH:mm:ss"),
							DateUtils.formatDate(busMileage.getEndDate(), "HH:mm:ss"),
							busMileage.getMileage(),
							busMileage.getDriverName(),
							JSON.toJSONString(busMileage)
					);
		}
		busMileages.add(busMileage);	// 添加到 里程统计 数组中，结束当前里程段的统计
		
		
		/*
		 * 重新初始化统计数据
		 * 	1、统计里程类型  0 运营 1 非运营
		 *  2、设置里程统计的 开始时间
		 *  2、新里程 默认 0 （对象初始化时候已经默认）
		 */
		Long timeDiffer = nextPoint == null ? null : nextPoint.getTime().getTime() - currentPoint.getTime().getTime();
		boolean isTimeSkip = timeDiffer == null ? false : timeDiffer > 60 * 1000 * 15; // 是否时间跳跃
		
		busMileage = new BusMileage();
		busMileage.setType(type);
		if(isTimeSkip){
			busMileage.setStartDate(nextPoint.getTime());
			busMileage.setDoduuid(nextPoint.getDriverUuid());
			busMileage.setDriverName(nextPoint.getDriverName());
		}else{
			busMileage.setStartDate(currentPoint.getTime());
			busMileage.setDoduuid(currentPoint.getDriverUuid());
			busMileage.setDriverName(currentPoint.getDriverName());
		}
		
		return busMileage;
	}


	public void saveBusMileageCaculate(BusMileageData entity) {

		saveToRedis(entity);
		saveToES(entity);
	}
	
	public void saveToRedis(BusMileageData entity){
		
		List<BusMileageSegment> segments = entity.mileageSegments;
		for (BusMileageSegment mileageSegment : segments) {
			
			dataStorageToRedisService.saveBusMileageToRedis(entity.date, mileageSegment.busEngile);
		}
		
	}
	
	public void saveToES(BusMileageData entity){
		List<ESPositionEntity> gpsPoints = new ArrayList<ESPositionEntity>();
		List<ESEnterOutEntity> enterOutPoints = new ArrayList<ESEnterOutEntity>();

		List<BusMileageSegment> mileageSegments = entity.mileageSegments;
		for (BusMileageSegment mileageSegment : mileageSegments) {
			
			List<TimingPoint> caculatePoints = mileageSegment.caculatePoints;
			for (TimingPoint timingPoint : caculatePoints) {
				gpsPoints.add(ESPositionEntityConvertUtils.convertToESTimingPointToPosiston(timingPoint));
			}
			
			List<TimingPoint> _enterOutPoints = mileageSegment.enterOutPoints;
			List<ESEnterOutEntity> enterout = dataStorageEnterOutService.getEnterOutData(_enterOutPoints);
			enterOutPoints.addAll(enterout);
		}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("date", entity.date);
		data.put("busUuid", entity.busUuid);
		data.put("busNumber", entity.plate);
		data.put("saveEnterOut", JSON.toJSONString(enterOutPoints));
		data.put("savePosition", JSON.toJSONString(gpsPoints));

		middlewareElasticsearchService.saveMileageCaculate(data);
	}
	
	public void clearBusMileageCaculate(BusMileageData entity){
		System.out.println("清空里程计算缓存信息");
	}
}
